<script lang="ts" setup>
import { computed } from 'vue'

import { transformFormSchema, useAddEditForm, useAddEditFormModal } from '#/hooks/useAddEditForm'

import type { UserItemForm } from '#/api/system/model/userModel'
import { $t } from '@vben/locales'
import { getAddEditFormSchema } from '../data/AddEditFrom'
import { PageApi } from '../use/api'

defineOptions({
    name: 'FormModelMenu'
})

defineEmits(['success'])

const { Form, formApi, formTitle, setRowId, setViewMode } = useAddEditForm<UserItemForm>({
    title: '图片导入',
    onAddSubmit(values) {
        return PageApi.add(values)
    },
    onEditSubmit({ values, rowId }) {
        delete values.password
        return PageApi.edit(rowId, values)
    }
})

const { Modal, modalApi } = useAddEditFormModal({
    formApi,
    onOpen({ record, isViewMode = false }) {
        setViewMode(isViewMode)
        if (isViewMode) {
            modalApi.setState({
                showConfirmButton: false,
                cancelText: $t('common.close')
            })
        } else {
            modalApi.setState({
                showConfirmButton: true,
                cancelText: $t('common.cancel')
            })
        }
        setRowId(record?.id ?? null)

        const schema = getAddEditFormSchema({
            formApi,
            rowId: computed(() => record?.id)
        })

        formApi.setState({
            // 更新表单数据
            schema: isViewMode ? transformFormSchema(schema) : schema
        })

        formApi.updateSchema([
            {
                fieldName: 'roleIds',
                defaultValue: (record?.roles ?? []).map((v: any) => v.id),
                componentProps: {
                    options: record?.roles ?? []
                }
            }
        ])

        // 回填表单数据
        if (record) {
            formApi.setValues(record)
        }
    }
})
</script>
<template>
    <Modal :title="formTitle">
        <Form />
    </Modal>
</template>
